<?php

namespace app\common\controller;
use think\Db;
use think\Request;
use think\Session;
use think\View;
use app\common\model\BackendUserModel;
use app\common\model\BackendRuleModel;
use app\common\model\ConfigModel;

class Backend extends Base
{
  protected $backendUser;
  protected $exportTable = "";
  protected $exportHeader = "";

  public function __construct(Request $request = null)
  {
  	//判断是否注册
  	$BackendUserModel = new BackendUserModel();
  	if($BackendUserModel->isLogin() === false&&$this->isRequestLogin()===true){
  		$this->redirect(Url('admin/backend_user/login'));
  	}
    //用户
    $this->backendUser = Session::get("backendUser");

    //超级用户
    $acceptUser = (new ConfigModel)->getConfigBykey('SUPER_ADMIN_ID');
    $acceptUser = explode(",", $acceptUser);
    Session::set("acceptUser", $acceptUser);

  	//权限验证
    $BackendRuleModel = new BackendRuleModel();
    $rule = $BackendRuleModel->setAllUserRule($this->backendUser['user_group_id']);
  	if(!in_array($this->backendUser['id'], $acceptUser)&&$BackendRuleModel->isAccept($rule) === false&&$this->isRequestLogin($request)===true){
      if(Request::instance()->isPost()){
        exit(json_encode(['status'=>400,'msg'=>'没有权限']));
      }else{
        $view = new View();
        echo $view->fetch('/public/no-authority');exit();
      }
    }
    parent::__construct($request);
  }

  //判断请求是否需要登录
  public function isRequestLogin(){
    $url = getRequestUrl();
		$requestUrl = "{$url['controller']}/{$url['action']}";
		if(in_array($requestUrl, ['backend_user/login','backend_user/register','backend_user/dologin','backend_user/doregister','backend_user/logout'])){
			return false;
		}
  	
  	return true;
  }

  //导出
  public function export(){
    if(empty($this->exportTable)){
      exit("没有exportTable！");
    }
    if(empty($this->exportHeader)||!is_array($this->exportHeader)){
      exit("没有exportHeader！");
    }

    $where = Session::get($this->exportTable."_where");
    $where = empty($where) ? [] : $where;
    $data = Db::table($this->exportTable)->where($where)->select();

    export($data, $this->exportHeader);
  }
}